\documentclass[11pt]{article}%

\usepackage[left=1.2in,right=1.2in]{geometry}
\usepackage[T1]{fontenc}
\usepackage{kpfonts}
% \usepackage{mathpazo}
% \linespread{1.05}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{enumerate}
\usepackage[bookmarks,bookmarksopen]{hyperref}

\pdfpagewidth 8.5in
\pdfpageheight 11.0in

\begin{document}

\title{COMP 303 - Software Development}
\author{Shen Chen Xu}
\maketitle

\tableofcontents

\section{A Crash Course in Java}

\section{The Object-Oriented Design Process}

\subsection{From Problem to Code}

Programming tasks originate from the desire to solve a particular problem. It
is a common practice to break up the software development process into three
phases:
\begin{itemize}
  \item Analysis
  \item Design
  \item Implementation
\end{itemize}
Of course, it is a simplistic to assume that development is a simple linear
progression through these phases: software products evolve over time.
Experience suggests that OO design can lead to software that facilitates this
evolution better than other traditional methods because objects and classes
tend to be fairly stable.

\subsubsection{The Analysis Phase}

The goal of the analysis phase is a complete description of what the software
should do. The result of this phase is a detailed textual description, commonly
called a \emph{functional specification}, that has the following
characteristics:
\begin{itemize}
  \item It completely defines the tasks to be performed.
  \item It is free from internal contradictions.
  \item It is readable both by experts in the problem domain and by software
    developers.
  \item It is reviewable by diverse interested parties.
  \item It can be tested against reality.
\end{itemize}

Consider the task of writing a word-processing program. The analysis phase must
define terms such as fonts, footnotes, multiple columns, the interaction of
those features, etc. The user interface must be documented, explaining how user
can enter and move a footnote, etc. One possible format of the output is a user
manual, precisely worded to remove as much ambiguity as possible.

Another common format for describing the behavior of a system is a set of
\emph{use cases}. A use case is a description of a sequence of actions that
yields a benefit for a user.

The analysis phase concerns with the description of \emph{what} needs to be
done, not how it should be done. The selection of algorithms and data
structures will be handled in the implementation phase.

\subsubsection{The Design Phase}

In the design phase, we structure the programming tasks into a set of
interrelated classes. Details such as the exact choice of data structures are
still not of concern in the design phase but is deferred until implementation.
Even the choice of programming language is not a design issue. The major goals
are:
\begin{itemize}
  \item Identify the classes.
  \item Identify the responsibilities of these classes.
  \item Identify the relationships among these classes.
\end{itemize}
These are goals, not steps. The discovery process is iterative. The end result
can include:
\begin{itemize}
  \item A textual description of the classes and their most important
    responsibilities.
  \item Diagrams of the relationships among the class.
  \item Diagrams of important usage scenarios.
  \item State diagrams of objects whose behavior is highly state-dependent.
\end{itemize}

\subsubsection{The Implementation Phase}

The goal is the programming, testing, and deployment of the software product.
Traditional programming methods rely on completion and unit testing, followed
by an integration phase, which tends to be frustrating and disappointing. OO
development encourages the gradual growth of a program by attaching more
working classes and class clusters and repeated testing.

It's common to defer the implementation of some features and build a ``rapid
prototype'' that display some functionality of the final product. This can be
helpful in influencing the design or even the problem analysis, and gives more
insights into the solutions that are really desired.

OO design is particularly suited for prototyping. The objects supporting the
prototype are likely to be the same that need to be present in the final
product, and growing the prototype into a complete program is often feasible.
However, be sure that the transition is well managed and enough time is
allocated to fix mistakes and implement newly discovered improvements.

\subsection{The Object and Class Concepts}

Objects are entities that have three characteristic properties:
\begin{itemize}
  \item State
  \item Behavior
  \item Identity
\end{itemize}

An object can store information that is the result of its prior operations.
That information may determine how the object behaves in the future. The
collection of all information held by an object is the object's \emph{state}.
Consider the example of a mailbox in a voice mail system. A mailbox object may
be in an empty state or full. This affects the behavior: a full mailbox may
reject new messages, whereas an empty mailbox may give a special response ``no
messages''.

The \emph{behavior} of an object is defined by the operations that an object
supports (and not supports). For example, a mailbox can add a mail message or
retrieve a stored message, but it can't translate a message into some language.

The state and behavior do not fully characterize an object. Two or more objects
can support the same operations and have the same state. Each object has its
own \emph{identity}.

Most OO programming languages support the grouping of similar objects into
classes. A \emph{class} describes a collection of related objects, which have
the same operations and possible states. A class definition includes the
following:
\begin{itemize}
  \item The operations that are allowed on the objects of the class.
  \item The possible state for objects of the class.
\end{itemize}
Objects that conform to a class description are called \emph{instances} of that
class.

\subsection{Identifying Classes}

To discover classes, look for \emph{nouns} in the problem description. Class
names should be nouns in the singular form. Unless solving a generic problem,
don't use generic names such as \texttt{Agent}, \texttt{Event}, etc. If you
name your classes after verbs, you are probably on the wrong track. Here are
some of the categories of classes:
\begin{itemize}
  \item Tangible things.
  \item Agents. For example, the \texttt{Scanner} class.
  \item Events and transactions. Useful to model records of activities. For
    example, the \texttt{MouseEvent} class.
  \item Users and roles. Found in systems that are used by more than one person
    or where one person needs to perform distinct tasks. For example, the
    \texttt{Administrator} class.
  \item Systems. They model a subsystem or the overall system being built.
    Typically used to perform initialization and shutdown.
  \item System interfaces and devices. They model the host operating system,
    hardware, etc. For example, the \texttt{File} class.
  \item Foundation classes. They are classes such as \texttt{String},
    \texttt{Date}, etc. You can assume that they already exist in the design
    state.
\end{itemize}

\subsection{Identifying Responsibilities}

To discover responsibilities, look for \emph{verbs} in the problem description.
A responsibility must belong to exactly one class. Consider the mailbox system.
Adding a message to a mailbox should be a responsibility of the
\texttt{Mailbox} class, not the \texttt{Message} class. Responsibilities of a
class should stay at \emph{one abstraction level}. Low level: files, keyboard,
mouse interface. High level: \texttt{MailSystem}.

\subsection{Relationships Between Classes}

\subsubsection{Dependency}

A class \emph{depends} on another class if it manipulates object of the other
class. For example, the \texttt{Mailbox} class \emph{uses} the
\texttt{Message} class. It's easier to understand when a class \emph{doesn't}
depend on another: if a class can carry out all its tasks without being aware
that the other class even exists. For example, the \texttt{Message} class does
not need to use the \texttt{Mailbox} class at all. This shows that dependency
is asymmetric.

One important design goal is to minimize the number of dependency
relationships, that is, to minimize the \emph{coupling} between classes. A low
degree of coupling tends to make it much easier to implement changes in the
future.

\subsubsection{Aggregation}

A class \emph{aggregates} another if its objects contain objects of the other
class. For example, \texttt{MessageQueue} aggregates \texttt{Message}.
Informally described as the ``has-a'' relationship. We can talk about the
\emph{multiplicities}: has exactly one, or has many. Fields of very simple type
such as number, string or date are not considered as aggregation.

\subsubsection{Inheritance}

a class \emph{inherits} from another if it incorporates the behavior of the
other class (its objects are special cases of objects of the other class),
but possibly with additional responsibilities and richer state. For example, we
can have a class \texttt{ForwardedMessage} inherit from the \texttt{Message}
class. We call the more general class the \emph{superclass} and the more
specialized class the \emph{subclass}. A subclass object must be usable in all
situations in which a super class is expected (Liskov substitution principle).
Inheritance is often called the ``is-a'' relationship.

\subsection{Use Cases}

Use cases are an \emph{analysis} technique to describe in a formal way how a
computer system should work. Each use case focuses on a specific scenario, and
describes the steps that are necessary to bring it to successful completion.
Each step represents an interaction with people or entities outside the system. 
An use case must yield a result that is of some \emph{value} to an actor. Many
scenarios can also fail for some reason, therefore an use case should include
\emph{variations} that describe these situations.

\subsection{CRC Cards}

The CRC card method is a \emph{design} technique for discovering classes,
responsibilities and relationships. It is an index card that describes a class,
its high-level responsibilities (not individual methods) and its
\emph{collaborators} (dependent class). They are small, so they disencourage
your from piling too much responsibility into a single class. Name on top,
responsibilities on the left, collaborators on the right. The CRC cards can be
useful for walking through use cases, particularly for group discussion.
Arranging them on the table so that classes are physically close to their
collaborators, this can give clues to simple or overly complex relationships.

The CRC cards are good for design, but not for documentation. They are
discovery tool, not archival information.

\subsection{UML Class Diagrams}

A UML diagram illustrates an aspect of an OO design, using a standardized
notation. A class is represented by a box, with name on top, followed by
attributes and methods, possibly with types specified.

(TODO: The arrows)

\subsection{Sequence Diagrams}

A sequence diagram shows the time ordering of a sequence of method calls.

(TODO: The diagrams)

\subsection{State Diagrams}

A state diagram shows the states of an object and the transition between
states. Think DFA.

\subsection{Using \texttt{javadoc} for Design Documentation}

\subsection{Case Study: A Voice Mail System}

\section{Guidelines for Class Design}

\subsection{An Overview of the Date Classes in the Java Library}

\texttt{Date}, \texttt{Calendar} and \texttt{GregorianCalendar}.

\subsection{Designing a Day Class}

\subsection{Three Implementations of the Day Class}

\subsection{The Importance of Encapsulation}

By using encapsulation, the users can be unaware of the implementation
details, and the implementators can change the implementation without
inconveniencing the users. Private data fields are essential for improving the
implementation of a class without disruption to its users.

\subsubsection{Accessors and Mutators}

\emph{Mutotars} change the state of an object, and \emph{accessors} read the
instance fields. Classes with no mutators are \emph{immutable}. There is no
need to supply mutators for every field or as a counterpart of every accessors,
because this may allow inconsistencies within an object. Suppose we have a
\texttt{Date} object representing March 31 and we set the month to February,
what happens? There is no February 31.

One advantage to immutable classes is that their object references can be
freely shared. In contrast, if an \texttt{Employee} class return a
\texttt{Date} object via the method \texttt{getHireDate} and the
\texttt{Date} class is mutable, then the state of the \texttt{Employee} object
can be changed! An accessor method should never return a reference to a mutable
instance field. The remedy is to return a clone. There can be a second problem.
When constructing an \texttt{Employee} object, a \texttt{Date} reference is
supplied, guess what happens. Again, clone the \texttt{Date} object in the
constructor.

\subsubsection{Final Instance Fields}

A final reference does not make the object immutable! Only the reference
itself!

\subsubsection{Separation of Accessors and Mutators}

A (better) alternative to the \texttt{next()} method of the \texttt{Scanner}
class:
\begin{itemize}
  \item \texttt{String getCurrent()}
  \item \texttt{next()}
\end{itemize}

\subsubsection{Side Effects}

Generally, the user of a method doesn't expect you to modify the external
arguments. Don't abuse \texttt{println} to report errors, throw an exception.

\subsubsection{The Law of Demeter}

Karl Lieberherr has formulated the \emph{Law of Demeter} that states that a
method should only use
\begin{itemize}
  \item Instance field of its class.
  \item Parameters.
  \item Objects that it constructs with \texttt{new}.
\end{itemize}
A method that follows the Law of Demeter does not operate on global objects or
objects that are a part of another object.

\subsection{Analyzing the Quality of an Interface}

\subsubsection{Cohesion}

A class is \emph{cohesive} if all of its methods are related to a single
abstraction.

\subsubsection{Completeness}

A class interface should be complete, it should support all operations that are
a part of the abstraction that the class represents.

\subsubsection{Convenience}

Before Java 5.0, you had to wrap \texttt{System.in} into an
\texttt{InputStreamReader} and then into a \texttt{BufferedReader}. This
problem was fixed with the \texttt{Scanner} class.

\subsubsection{Clarity}

\subsubsection{Consistency}

For example, always starts indices at 0 (or at 1, but be consistent).

\subsection{Programming by Contract}

Once we ensure that all constructors of a class create only objects with valid
state and that all mutator operations preserve the valid state, then we can
never have invalid objects.

\subsubsection{Preconditions}

A \emph{precondition} is a condition that must be true before the method may be
called. For example, a stack must be non-empty before a \texttt{pop()} call. A
precondition must be checkable by the caller. For example, a precondition on a
private field might need an accessor so that the caller can check it.

\subsubsection{Assertions}

An \emph{assertion} is a condition that a programmer expects to be true. Assert
the precondition. Can be turned off though.

Would it be ``nicer'' to drop preconditions and instead do nothing or return
``harmless'' values if the preconditions are not met? This is not a benefit for
the caller, as the caller might be expecting the postcondition to be fulfilled.

\subsubsection{Exceptions in the Contract}

Part of the contract. For example, failure in opening a file. The existence of
a file is not really checkable since a program might remove it immediately
after the check.

\subsubsection{Postconditions}

A \emph{postcondition} of a method is a condition that holds after the method
has completed, provided that the precondition was fulfilled when it was called.
If a postcondition is not fulfilled, you should \emph{not} throw an exception.
After all, that is a failure in your own code. But you can use assertions.

\subsubsection{Class Invariants}

A \emph{class invariant} is a condition that holds for all objects of a class
after the completion of any constructor or method. We distinguish between
interface invariants and implementation invariants. Interface invariants are of
interest to the user because they give behavior guarantees for any object of
the class. Implementation invariants can be used by the implementator to ensure
correctness of implementations. Note that interface invariants must be stated
in terms of the public interface.

\subsection{Unit Testing}

A \emph{unit test} of a class tests the class in isolation.

\section{Interface Types and Polymorphism}

A class defines a set of operations (the interface) \emph{and} statements that
specify how to carry out the operations and how to represent object state (the
implementation). However, it is often useful to \emph{separate} the interface
concept from that of a class. This can help in the development of reusable
code. Multiple classes can \emph{implement} the same interface, which makes it
possible to write programs that can operate on a mixture of objects from any of
these classes. This behavior is called \emph{polymorphism}.

\subsection{The \texttt{Icon} Interface Type}

You can display a dialog box with the following call:
\begin{verbatim}
JOptionPane.showMessageDialog(
        null, // parent window
        "Hello World!", // message
        "Message", // window title
        JOptionPane.INFORMATION_MESSAGE, // message type
        new ImageIcon("icon.jpg"));
\end{verbatim}
The signiture of this method is actually:
\begin{verbatim}
public static void showMessageDialog(
        Component parent,
        Object message,
        String title,
        int messageType,
        Icon anIcon);
\end{verbatim}
Note that the last parameter is of type \texttt{Icon}. The \texttt{ImageIcon}
class implements the \texttt{Icon} \emph{interface type}. If a method has a
parameter of an interface type, then you can supply an object of any class that
implements that interface. An interface specifies a set of methods, but it does
not implement them. When a class implements an interface type, it defines
implementations for the methods that the interface type specifies. All methods
of an interface type are automatically public, that's whole purpose of an
interface. An interface cannot specify instance variables, they are
implementation details. The interface only specifies \emph{what} needs to be
done, not how to do it.

However, it is legal to supply variables in an interface definition. These
variables are automatically declared as \texttt{public static final}. Also, an
interface can extend another interface by adding additional requirements.

\subsection{Polymorphism}

The type of an object is never an interface type. However, the type of a
variable can be an interface type. Such a variable contains a reference to an
object whose class implements the interface type. The actual method will be
looked up at runtime. The ability to select the appropriate method for a
particular object is called \emph{polymorphism}.

An important use of polymorphism is to promote \emph{loose coupling}. The
implementation class is decoupled with the class that uses the interface type.
Another important use of polymorphism is \emph{extensibility}. By using an
interface type, the designers don't lock you into the use of a particular
implementation.

\subsection{The \texttt{Comparable} Interface Type}

\subsection{The \texttt{Comparator} Interface Type}

\subsection{Anonymous Classes}

What if you need a particular comparator only once?
\begin{verbatim}
Comparator<Country> comp = new
    Component<Country>()
    {
        public int compare(Country c1, Country c2)
        {
            return c1.getName().compareTo(c2.getName());
        }
    };
\end{verbatim}
You can create multiple objects of the anonymous class, simply by putting the
construction inside a method and returning it.

\subsection{Frames and User Interface Components}

A frame window is a top-level window, usually decorated with borders and a
title bar.
\begin{verbatim}
JFrame frame = new JFrame();
frame.pack();
frame.setVisible(true);
\end{verbatim}
The \texttt{pack} command sets the size of the frame to the smallest size
needed. Alternatively, you can use the $setSize$ method. If you don't pack the
frame or set its size, the window is displayed at size $0$ by $0$ pixels.
\begin{verbatim}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
\end{verbatim}
This exits the program when the user closes the window.
\begin{verbatim}
JButton helloB = new JButton("Say Hello");
JButton byeB = new JButton("Say Goodbye");
final JTextField textField = new TextField(width);
frame.setLayout(new FlowLayout());
frame.add(helloB);
frame.add(byeB);
frame.add(textField);
\end{verbatim}

\subsection{User Interface Actions}

To define the action of a button, add an object of a class that implements the
\texttt{ActionListener} interface type. When the button is clicked, the code of
the \emph{actionPerformed} method is executed.
\begin{verbatim}
helloB.addActionListener(new
    ActionListener()
    {
        public void actionPerformed(ActionEvent event)
        {
            textField.setText("Hello, World");
        }
    });
\end{verbatim}
Methods of inner classes can access variables that are visible in the enclosing
scope. If you access a \emph{local} variable, that variable must be declared as
\texttt{final}. Side note, the inner class actually automatically create a copy
for each variable that it uses in the enclosing scope (that's why
\texttt{final}).

\subsection{Timers}

\subsection{Drawing Shapes}

\subsection{Designing an Interface Type}

\section{Patterns and GUI Programming}

A \emph{pattern} is a description of a problem and its solution that you can
apply to many programming situations.

\subsection{The Iterator as a Pattern}

Why does the Java library use an iterator to traverse a linked list? Iterator
do not expose the internal structure of a collection class, reducing the risk
of messing up the links and corrupt the link structure.
\begin{verbatim}
LinkedList<String> list = ...;
ListIterator<String> iter = list.listIterator();
while (iter.hasNext()) {
    String current = iter.next();
    ...
}
\end{verbatim}
Also, iterators are preferred over lists with a cursor because you can attach
more than one iterator to a collection. Furthermore, the iterator concept is
useful outside the domain of collection classes. For example, the
\texttt{Scanner} is an iterator through the tokens in a character sequence. An
\texttt{InputStream} is an iterator through the bytes of a stream. This makes
the iterator into a \emph{pattern}.

\subsection{The Pattern Concept}

The architect Christopher Alexander formulated over 250 patterns for
architectural design. Those patterns lay down rules for building houses and
cities. Alexander uses a very distinctive format for these rules. Ever pattern
has:
\begin{itemize}
  \item A short \emph{name}.
  \item A brief description of the \emph{context}.
  \item A lengthy description of the \emph{problem}.
  \item A prescription for a \emph{solution}.
\end{itemize}
A pattern presents proven advice in a standard format. Because that solution
has been successful in the past, there is a good chance that you will benefit
from it as well.

The \textsc{Iterator} pattern teaches how to access the elements of an
aggregate object:
\begin{description}
  \item[Context]
    \begin{enumerate}
      \item An object (aggregate) contains other objects (elements).
      \item Clients (methods that use the aggregate) need access to the
        elements.
      \item The aggregate should not expose its internal structure.
      \item There may be multiple clients that need simultaneous access.
    \end{enumerate}
  \item[Solution]
    \begin{enumerate}
      \item Define an iterator class that fetches one element at a time.
      \item Each iterator object needs to keep track of the position of the next
        element to fetch.
      \item If there are several variations of the aggregate and iterator
        classes, it is best if they implement common interface types. Then the
        client only needs to know the interface types, not the concrete
        classes.
    \end{enumerate}
\end{description}

Design patterns give you constructive advice. \emph{Antipatterns} are the
opposite of design patterns--examples of design that are so bad that you should
avoid them at all cost. Among the commonly cited antipatterns are:
\begin{itemize}
  \item The Blob: A class that has gobbled up many disparate responsibilities.
  \item The Poltergeist: A spurious class whose objects are short-lived and
    carry no significant responsibilities.
\end{itemize}

\subsection{The \textsc{Observer} Pattern}

Have you ever used a program that shows you two editable views of the same
data, such as WYSIWYG and a structural view of a document? When you edit one of
the views, the other updates automatically and instantaneously. The key to
implementing this behavior is the \emph{model/view/controller architecture}.
One object, the \emph{model}, holds the information in some data structure. The
model has no visual appearance, it just holds the raw data. Several other
objects, the \emph{views}, draw the visible parts of the data in a format that
is specific to each view. Finally, each view has a \emph{controller}, an object
that processes user interaction. The controller may process mouse and keyboard
events from the windowing system, or it may contain user interface elements
such as buttons and menus.

Here is what happens when a user perform an action:
\begin{itemize}
  \item The controller tells the model what change to make.
  \item The model makes the change and inform all the views.
  \item All views repaint themselves.
  \item During painting, each view asks the model for the current text.
\end{itemize}
This minimizes the coupling between the model, views and controllers. The model
knows nothing about the views, except that they need to be notified of all
changes. The views know nothing of the controllers. It is easy to add more
views to a model, and to change the controller of a view.

The model knows about a number of \emph{observers}, namely, the views. In
Chapter 4, an event source such as a button holds a number of \emph{listeners}.
This button knows nothing about its listeners except that they implement a
particular interface type.

The fact that this arrangement occurs as a solution in two separate problems
shows that it may be useful to distill the solution into a pattern. This
notification pattern is called the \textsc{Observer} pattern:
\begin{description}
  \item[Context]
    \begin{enumerate}
      \item An object (subject) is the source of events.
      \item One or more objects (observers) want to know when an event occurs.
    \end{enumerate}
  \item[Solution]
    \begin{enumerate}
      \item Define an oberserver interface type. Observer classes must
        implement this interface type.
      \item The subject maintains a collection of observer objects.
      \item The subject class supplies methods for attaching observers.
      \item Whenever an event occurs, the subject notifies all observers.
    \end{enumerate}
\end{description}

\subsection{Layout Managers and the \textsc{Strategy} Pattern}

You add user interface components to a \emph{container}. The container put it
somewhere on the screen. In some GUI toolkits, the programmer (or a layout
tool) specifies the pixel position for each component. However, that is not a
good idea: Different GUI ``look and feel'' and different languages might cause
problems. Java uses a layout manager arranges the components in a container.

\subsubsection{Using Predefined Layout Managers}

There are several built-in layout managers in Java: \texttt{FlowLayout},
\texttt{BoxLayout}, \texttt{BorderLayout}, \texttt{GridLayout},
\texttt{GridBagLayout}, etc.
\begin{verbatim}
JPanel keyPanel = new JPanel();
keyPanel.setLayout(new GridLayout(4, 3));
\end{verbatim}

\subsubsection{Implementing a Custom Layout Manager}

It is not difficult to write your own layout manager.
\begin{verbatim}
public interface LayoutManager
{
    Dimension minimumLayoutSize(Container parent);
    Dimension preferredLayoutSize(Container parent);
    void layoutContainer(Container parent);
    void addLayoutComponent(String name, Component comp);
    void removeLayoutComponent(Component comp);
}
\end{verbatim}

\subsubsection{The \textsc{Strategy} Pattern}

The \textsc{Strategy} pattern teaches how to supply variant of an algorithm:
\begin{description}
  \item[Context]
    \begin{enumerate}
      \item A class (context class) can benefit from different variants of an
        algorithm.
      \item Clients of the context sometimes want to supply custom versions of
        the algorithm.
    \end{enumerate}
  \item[Solution]
    \begin{enumerate}
      \item Define an interface type that is an abstraction for the algorithm.
        We'll call this interface type the \emph{strategy}.
      \item Concrete strategy classes implement the strategy interface type.
        Each strategy class implements a version of the algorithm.
      \item The client supplies a concrete strategy object ot the context
        class.
      \item Whenever the algorithm needs to be executed, the context class
        calls the appropriate methods of the strategy object.
    \end{enumerate}
\end{description}

Another manifestation of the \textsc{Strategy} pattern is the
\texttt{Comparator} interface.

\subsection{Components, Containers, and the \textsc{Composite} Pattern}

User interface components are contained in containers. If a \texttt{JPanel} can
contain other components, it must be a \texttt{Container}. But if we want to
add it to the frame, it must also be a \texttt{Component}. Can a container
itself be a component?

The \textsc{Composite} pattern teaches how to combine several objects into an
object that has the same behavior as its parts. For example, a program that
deals with selling items. It is sometimes useful to sell a \emph{bundle} of
items as if it were a single item. One characteristic of the \textsc{Composite}
pattern is how a method of the composite object does its work: It must apply
the method to all of its primitive objects and then combine the results. For
example, compute the price of a bundle by adding up the price of each item.
\begin{description}
  \item[Context]
    \begin{enumerate}
      \item Primitive objects can be combined into composite objects.
      \item Clients treat a composite object as a primitive object.
    \end{enumerate}
  \item[Solution]
    \begin{enumerate}
      \item Define interface type that is an abstraction for the primitive
        objects.
      \item A composite object contains a collection of primitive objects.
      \item Both primitive classes and composite classes implement that
        interface type.
      \item When implementing a method, the composite class applies the same
        method to its primitive objects and combines the results.
    \end{enumerate}
\end{description}

\subsection{Scroll Bars and the \textsc{Decorator} Pattern}

Here's how you add scroll bars to a text area:
\begin{verbatim}
JTextArea area = new JTextArea(10, 25);
JScrollPane scroller = new JScrollPane(area);
\end{verbatim}
Because the scroll bars add functionality to the underlying text area, they are
called a \emph{decoration}. The \textsc{Decorator} pattern teaches how to form
a class that adds functionality to another class while keeping its interface.
\texttt{JScrollPane} decorates a component \emph{and is again a component}. A
key aspect of the \textsc{Decorator} pattern is that the decorated component is
entirely passive. The text area does nothing to acquire scroll bars.

There are two advantages. First, it would be a bother if lots of different
components (text areas, panels, tables, etc.) would each have to supply an
option for scroll bars. Moreover, there is a potentially unbounded set of
decorations, and the component class can't anticipate all of them.

As with the \textsc{Composite} pattern, we note that the decorator implements a
method from the component interface by invoking the same method on the
component and then augmenting the result. For example, the \texttt{paint}
method of a scroll pane paints the decorated component and also the scroll bar.

\begin{description}
  \item[Context]
    \begin{enumerate}
      \item You want to enhance the behavior of a class (the component class).
      \item A decorated component can be used as the same way as a plain
        component.
      \item The component class does not want to take on the responsibility of
        the decoration.
      \item There may be an open-ended set of possible decorations.
    \end{enumerate}
  \item[Solution]
    \begin{enumerate}
      \item Define an interface type that is an abstraction for the component.
      \item Concrete component classes implement this interface type.
      \item Decorator classes also implement this interface type.
      \item A decorator object manages the component object that is decorates.
      \item When implementing a method, the decorator classes applies the same
        method to the decorated component and combines the result with the
        effect of the decoration.
    \end{enumerate}
\end{description}
A decorator enhances the behavior of a \emph{single} component, whereas a
composite collects \emph{multiple} components. A decorator aims to enhance,
whereas a composite merely collects.

\subsubsection{Stream Decorators}

Another example for the \textsc{Decorator} pattern is the set of stream filters
in the I/O library.
\begin{verbatim}
BufferedReader in = new BufferedReader(new FileReader("input.txt"));
String firstLine = in.readLine();
\end{verbatim}
Another example, the \texttt{PushbackReader} which allows ``peek ahead'' at
input.
\begin{verbatim}
PushbackReader reader = new PushbackReader(new FileReader("input.txt"));
char c = reader.read();
if (...) reader.unread(c);
\end{verbatim}
Other common decorators for readers are decryptors and decompressors.

\subsection{How to Recognize Patterns}

The description of many patterns look superficially alike. One solution is to
focus on the \emph{intent} of the pattern: \textsc{Composite} pattern groups
components into a whole, \textsc{Decorator} pattern enhances a component, and
\textsc{Strategy} pattern wraps an algorithm into a class. Another solution is
to remember a place where the pattern is put to use: \textsc{Strategy} pattern
is used for layout managers and \textsc{Decorator} is used for scroll bars.

\subsection{Putting Patterns to Work}

\section{Inheritance and Abstract Classes}

\subsection{The Concept of Inheritance}

\subsubsection{Using Inheritance for Modeling Specialization}

Specialized subclasses inherit from (non-\texttt{final}) superclasses that
represent more general concepts. A subclass inherits the methods of the
superclass, can define additional methods and fields, but can also override
(non-\texttt{final}) methods by giving a new definition.

\subsubsection{The Super/Sub Terminology}

\subsubsection{Inheritance Hierarchies}

A tree rooted at the \texttt{Object} class.

\subsubsection{The Substitution Principle}

According to the \emph{Liskov substitution principle}, you can use a subclass
object whenever a superclass object is expected. Note that polymorphism shows
up here.

\subsubsection{Invoking Superclass Methods}

A subclass cannot access private features of its superclass, you should use
accessors. Use the \texttt{super} keyword if the method is overridden.

\subsubsection{Invoking Superclass Constructors}

Use the \texttt{super} keyword to call a superclass constructor \emph{at the
start} of a subclass constructor. If a subclass constructor does not do so,
then the default superclass constructor with no parameter is called
automatically. If all superclass constructor require parameters, then the
subclass must call \texttt{super}.

\subsubsection{Preconditions and Postconditions of Inherited Methods}

A subclass method can only require a precondition that is \emph{at most as
strong} as the precondition of the method that it overrides. A subclass method
must ensure a postcondition that is \emph{at least as strong} as the
postcondition of the method that it overrides.

\subsection{Graphics Programming with Inheritance}

\subsection{Abstract Classes}

An abstract method is undefined and must be defined in a subclass. A class with
one or more abstract methods must be declared as abstract. You cannot construct
objects of an abstract class. An abstract class is somewhere between an
interface and a concrete class. It requires that subclasses implement methods
with a given signature. However, an abstract class usually has some
implementation. Abstract classes can define common behavior, but a class can
only extend one abstract class.

\subsection{The \textsc{Template Method} Pattern}

The \textsc{Template Method} pattern teaches how to supply an algorithm for
multiple types, provided that the sequence of steps does not depend on the
type:
\begin{description}
  \item[Context]
    \begin{enumerate}
      \item An algorithm is applicable for multiple types.
      \item The algorithm can be broken down into \emph{primitive operations}.
        The primitive operations can be different for each type.
      \item The order of the primitive operations in the algorithm doesn't
        depend on the type.
    \end{enumerate}
  \item[Solution]
    \begin{enumerate}
      \item Define an abstract superclass that has a method for the algorithm
        and abstract methods for the primitive operations.
      \item Implement the algorithm using the (abstract) primitive operation
        without implementing them.
      \item Each subclass defines the primitive operations but not the
        algorithm.
    \end{enumerate}
\end{description}

\subsection{Protected Interfaces}

A protected feature can be accessed by the methods of all subclasses. This is
useful when you don't what anything other than object of subclasses to have
access. As an added security measure, methods can use protected features only
on objects \emph{of their own class}. However, protected fields should be
avoided. They have the same disadvantages as public fields.

In Java, classes in the same \emph{package} also have access to protected
features.

\subsection{The Hierarchy of Swing Components}

\subsection{The Hierarchy of Standard Geometric Shapes}

\subsection{The Hierarchy of Exception Classes}

\subsection{When Not to Use Inheritance}

Use inheritance for \emph{is-a} relationships, aggregation for \emph{has-a}
relationships. Don't use inheritance if it violates the Liskov substitution
principle.

\section{The Java Object Model}

\subsection{The Java Type System}

\subsubsection{Types and Subtypes}

A \emph{type} is a set of values together with a set of operations that can be
applied to the type. Every \emph{type} in Java is one of the following:
\begin{enumerate}
  \item A primitive type (\texttt{int}, \texttt{short}, \texttt{long},
    \texttt{byte}, \texttt{char}, \texttt{float}, \texttt{double},
    \texttt{boolean}).
  \item A class type.
  \item An interface type.
  \item An array type.
  \item The null type.
\end{enumerate}
Every \emph{value} in Java is one of the following:
\begin{enumerate}
  \item A value of a primitive type.
  \item A reference to an object of a class.
  \item A reference to an array.
  \item \texttt{null}.
\end{enumerate}
A type \texttt{S} is a \emph{subtype} of the type \texttt{T} if
\begin{enumerate}
  \item \texttt{S} and \texttt{T} are the same type.
  \item \texttt{S} and \texttt{T} are both class types and \texttt{S} is a
    direct or indirect subclass of \texttt{T}.
  \item \texttt{S} and \texttt{T} are both interface types and \texttt{S} is a
    direct or indirect subinterface of \texttt{T}.
  \item \texttt{S} is a class type, \texttt{T} is an interface type, and
    \texttt{S} or one of its superclasses implements the interface type
    \texttt{T} or one of its subinterfaces.
  \item \texttt{S} and \texttt{T} are both array types and the component type
    of \texttt{S} is a subtype of the component type of \texttt{T}.
  \item \texttt{S} is not primitive type and \texttt{T} is the type
    \texttt{Object}.
  \item \texttt{S} is an array type and \texttt{T} is the type
    \texttt{Cloneable} or \texttt{Serializable}.
  \item \texttt{S} is the null type and \texttt{T} is not a primitive type.
\end{enumerate}
You can substitute a value of a subtype whenever a \emph{supertype} value is
expected.

\subsubsection{Array Types}

\begin{verbatim}
Rectangle[] r = new Recognize[10];
Shape[] s = r;
s[0] = new Polygon(...);
\end{verbatim}
Throws \texttt{ArrayStoreException} at runtime. Every array object remembers
its component type.

\subsubsection{Wrappers for Primitive Types}

Use wrapper classes when you need to supply primitive values to services that
require objects. Auto-boxing is the automatic conversion of a primitive type
value into an object of a wrapper class.

\subsubsection{Enumerated Types}

\begin{verbatim}
public enum Size { SMALL, MEDIUM, LARGE };
\end{verbatim}
The \texttt{enum} keyword defines a class with a private constructor and a
finite number of instances. It is equivalent to the following:
\begin{verbatim}
public class Size
{
    private Size() {}
    public static final Size SMALL = new Size();
    public static final Size MEDIUM = new Size();
    public static final Size LARGE = new Size();
}
\end{verbatim}
Note that an \texttt{enum} varaible can be \texttt{null}.

Because enumerated types are classes, you can add methods and instance fields.
You can also supply constructors, but they can only be used to construct the
enumeration values. For example
\begin{verbatim}
public enum Size
{
    SMALL(0.5), MEDIUM(1), LARGE(2);
    private Size(double value) { this.value = value; }
    public double getValue() { return value; }
    private double value;
}
\end{verbatim}

All enumeration classes automatically extend the \texttt{Enum} class, from
which they inherit a number of useful methods. In particular, the
\texttt{toString} method yields the name an enumerated constant. The
\texttt{Enum} class also implements the \texttt{Comparable} interface.

\subsection{Type Inquiry}

The \texttt{instanceof} operator tests whether the type of an object is a
subtype of the a given type, but it won't give you the exact type. You might
use it before you apply a cast. Note, \texttt{null instanceof T} always return
\texttt{false}. If you have any object reference, you can find the actual type
of the object using \texttt{object.getClass()}. Also, adding the suffix
\texttt{.class} to a type name yields the \texttt{Class} object that describes
the type:
\begin{verbatim}
Class c = Rectangle.class;
\end{verbatim}
Or:
\begin{verbatim}
Class c = Class.forName("java.awt.Rectangle");
\end{verbatim}
There is only one \texttt{Class} object for every type that has been loaded
into the virtual machie, so you can use the \texttt{==} test.

For array objects:
\begin{verbatim}
double[] a = new double[10];
Class c = a.getClass();
if (c.isArray())
    System.out.println("Component type=" + c.getComponentType());
\end{verbatim}
For historical reasons, the \texttt{getName} method produces strange-looking
names for array types. For example, \texttt{String[][].class.getName()} gives
\texttt{"[[Ljava.lang.String"}. In general:
\begin{center}
  \begin{tabular}{ll}
    \texttt{[type} & array type \\ \hline
    \texttt{B} & \texttt{byte} \\
    \texttt{C} & \texttt{char} \\
    \texttt{D} & \texttt{double} \\
    \texttt{F} & \texttt{float} \\
    \texttt{I} & \texttt{int} \\
    \texttt{J} & \texttt{long} \\
    \texttt{L}\textit{name} & class or interface \\
    \texttt{S} & \texttt{short} \\
    \texttt{Z} & \texttt{boolean}
  \end{tabular}
\end{center}

\subsection{The \texttt{Object} Class}

The \texttt{Object} class is the common superclass of all other Java classes.
It provides several important the methods.

\subsubsection{The \texttt{toString} Method}

The \texttt{toString} method is automatically applied
\begin{itemize}
  \item When you concatenate an object with a string.
  \item When you print an object with the \texttt{print} or \texttt{println}
    method.
  \item When you pass an object reference $e$ to and \texttt{assert} statement
    of the form \texttt{assert} \textit{condition} \texttt{:}
    $e$\texttt{;}
\end{itemize}
The default implementation in the \texttt{Object} class returns the name of the
class and the hash code of the object. It is a good idea to implement it in
your own classes.

\subsubsection{Equality Testing}

There are some technical requirements that the Java Language Specification
imposes on \texttt{equals} method:
\begin{itemize}
  \item It is \emph{reflexive}.
  \item It is \emph{symmetric}.
  \item It is \emph{transitive}.
  \item For any non-\texttt{null} reference value \texttt{x},
    \texttt{x.equals(null)} should return \texttt{false}.
\end{itemize}
A perfect \texttt{equals} method starts out like this:
\begin{verbatim}
public boolean equals(Object obj)
{
    if (this == obj) return true;
    if (obj == null) return false;
    if (getClass() != obj.getClass()) return false;
}
\end{verbatim}
For subclasses, it may be necessary to invoke the superclass version of the
\texttt{equals} method.

\subsubsection{Hashing}

The \texttt{hashCode} must be consistent with the \texttt{equals} method, that
is, if \texttt{x.equals(y)}, then \textit{x.hashCode() == y.hashCode()}.

\subsection{Shallow and Deep Copy}

To define a \texttt{clone} method, a class must minimally implement the
\texttt{Cloneable} interface type and override the \texttt{clone method}. The
\texttt{Cloneable} interface has no methods, it is just a ``taggin'' interface
type for testing whether an object is cloneable. If the object to be cloned
isn't an instance of a class that impelements \texttt{Cloneable}, it throws a
\texttt{CloneNotSupportedException}, which is a checked exception (must declare
it or catch it).

Why all the fuss? The \texttt{Object.clone} makes a \emph{shallow copy}. You
can define your own \texttt{clone} to make a ``sufficiently deep copy''.

\subsection{Serialization}

Serialization denotes the process of storing an object and its dependent
objects in a stream.
\begin{verbatim}
Employee[] staff = new Employee[2];
staff[0] = new Employee();
staff[2] = new Employee();
ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("staff.dat"));
out.writeObject(staff);
out.close();

ObjectInputStream in = new ObjectInputStream(
        new FileOutputStream("staff.dat"));
staff = (Employee[]) in.readObject();
in.close();
\end{verbatim}
Objects of classes that implement the \texttt{Serializable} interface (which is
also a tagging interface) can be serialized in object streams. If you don't
want to store a field, or a field is not serializable, declare it as
\texttt{transient}.

You can supply special methods
\begin{verbatim}
private void writeObject(ObjectOutputStream out);
private void readObject(ObjectInputStream in);
\end{verbatim}
These methods must first call \texttt{defaultWriteObject/defaultReadObject} and
then manually write or read the remaining information.

\subsection{Reflection}

\subsection{Generic Types}

\end{document}
